package com.ffyc.ssm.controller;

import com.ffyc.ssm.common.CommonResult;
import com.ffyc.ssm.modle.Ad;
import com.ffyc.ssm.modle.Admin;
import com.ffyc.ssm.service.AdService;
import com.ffyc.ssm.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@Transactional
@RequestMapping(path = "/ad")
public class AdController {

    @Autowired
    private AdService service;

    @GetMapping(path = "/list")
    public CommonResult showAdList(Ad ad){
        CommonResult<List> commonResult = null;
        try {
            List<Ad> list = service.findAdList(ad);
            if (list!=null){
                commonResult = new CommonResult<>(200,"查询成功" , list);
            }
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult<>(500,"查询失败" , null);
        }
        return commonResult;
    }

    //上传广告图
    @PostMapping(path = "/fileUpload")
    public  CommonResult fileUpload(@RequestParam("fileName") CommonsMultipartFile file,@RequestParam("adPosition") Integer adPosition,@RequestParam("url") String url){
        CommonResult<String> commonResult =null;
        File f0 =new File("D:\\userImg\\ad");
        if (!f0.exists()){
            f0.mkdir();
        }
        String imgName = file.getOriginalFilename();
        String newFileName =StringUtil.newFileName(imgName);
        File f =new File(f0,imgName);
        try {
            file.transferTo(f);
            System.out.println(adPosition);
            System.out.println(url);
            Ad ad = new Ad();
            ad.setAdPosition(adPosition);
            ad.setImgSrc(newFileName);
            ad.setUrl(url);
            service.uploadAd(ad);
            commonResult=new CommonResult(200,"上传成功",imgName);
        } catch (IOException e) {
            e.printStackTrace();
            commonResult =new CommonResult(500,"上传失败",null);
        }
        return  commonResult;
    }



    @PostMapping(path = "delete")
    public CommonResult save(Integer id){
        CommonResult commonResult = null;
        try {
            service.deleteAd(id);
            commonResult = new CommonResult<>(200,"查询成功" , null);
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult<>(500,"查询失败" , null);
        }
        return commonResult;
    }






}
